package com.wolfalpha.utron.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormal4Activity;
import com.wolfalpha.utron.adapter.ItemIdeaCommentAdapter;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.Idea;
import com.wolfalpha.utron.bean.IdeaComment;
import com.wolfalpha.utron.service.IdeaService;
import com.wolfalpha.utron.service.impl.IdeaServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
//import com.wolfalpha.utron.utils.ImageLoader;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.ScrollXListView;
import com.wolfalpha.utron.view.XListView;

import java.util.ArrayList;
import java.util.List;

import easemob.chatuidemo.activity.ChatActivity;

/**
 * 创意详情界面
 * <p/>
 * Created by luodon on 15/8/27.
 */

public class IdeaDetailActivity extends BaseNormal4Activity implements AdapterView.OnItemClickListener, View.OnClickListener, OnItemLongClickListener, XListView.IXListViewListener {

    private ScrollXListView lvComments;        //评论列表控件

    private TextView tvWhy;             //w为什么
    private TextView tvWhat;            //标题
    private TextView tvHow;             //怎么做？
    private TextView tvFrom;            //来源
    private TextView tvDir;            //方向
    private TextView tvTime;            //时间
    private TextView tvName;            //用户昵称
    private CircleImageView cvHead;     //用户头像

    private TextView tvTlz;             //讨论组
    private TextView tvWill;            //愿意加入讨论组

    private TextView tvGood;            //点赞
    private TextView tvBad;             //反对
    private TextView tvViews;           //浏览次数
    private List<IdeaComment> comments = new ArrayList<IdeaComment>();

    private int ideaId;                 //创意ID
    private int toUserId;               //回复对象ID

    private Drawable badSelected;
    private Drawable badNormal;
    private Drawable goodSelected;
    private Drawable goodNormal;

    private IdeaService ideaService;

//    private ImageLoader imageLoader;

    private final int LOAD_FINISH = 1;          //网页加载完成
    private final int LOAD_MORE = 3;        //刷新
    private final int LOAD_REFRESH = 2;        //刷新
    private final int DIALOG_DISMISS = 6;       //关闭比对话框

    private Idea idea = null;                   //创意实体

    private int page = 1;                       //评论页面

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOAD_FINISH:
                    if (idea == null) break;
                    final List<String> data = StringUtils.getDirsValues(IdeaDetailActivity.this);
                    Picasso.with(IdeaDetailActivity.this)
                            .load(idea.getUser_head())
                            .placeholder(R.mipmap.head_default)
                            .into(cvHead);
                    tvTime.setText(StringUtils.friendly_time(idea.getTime()));
                    tvFrom.setText("来自:  " + idea.getFrom());
                    tvBad.setText(String.valueOf(idea.getBad()));
                    tvGood.setText(String.valueOf(idea.getGood()));
                    tvViews.setText(String.valueOf(idea.getViews()));
                    tvWhat.setText(idea.getWhat());
                    tvWhy.setText(idea.getWhy());
                    tvDir.setText(data.get(idea.getDir() - 1001));
                    tvName.setText(idea.getUser_name());
                    if (idea.getHow() != null) {
                        tvHow.setText(idea.getHow());
                    }
                    if (idea.getTlz_id() != 0) {
                        tvTlz.setClickable(true);
                        tvTlz.setVisibility(View.VISIBLE);
                        tvTlz.setText("讨论ing: " + idea.getTlz_name());
                        tvTlz.setClickable(true);
                    } else {
                        tvWill.setVisibility(View.VISIBLE);
                        //如果是自己的想法，点击创建
                        if (AppContext.getInstance().getUserId() == idea.getUser_id()) {
                            //创建讨论组
//                            tvWill.setText("(" + String.valueOf(idea.getWillers()) + "人关注中) 点击创建讨论组");
                            tvWill.setText("已有(" + idea.getWillers() + "人)关注");
                        } else {
                            tvWill.setText("点击加关注(" + String.valueOf(idea.getWillers()) + "人)");
                            tvWill.setClickable(true);
                        }

                    }
                    break;
                case LOAD_REFRESH:
                    commentAdapter.setData(comments);
                    lvComments.stopRefresh();
                    break;
                case LOAD_MORE:
                    commentAdapter.setData(comments);
                    lvComments.stopLoadMore();
                    break;
                case DIALOG_DISMISS:
                    if (pd.isShowing()) {
                        pd.dismiss();

                    }
                    break;
            }
        }
    };
    private ItemIdeaCommentAdapter commentAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null || !bundle.containsKey("ideaId")) {
            finish();
        } else {
            ideaId = bundle.getInt("ideaId");
        }

        setContentView(R.layout.activity_idea_detail);
        ideaService = new IdeaServiceImpl();

        intiView();
        initListeners();
        loadData();
    }

    /**
     * 加载列表的数据
     */
    private void loadData() {


        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                idea = ideaService.getDetail(ideaId);
                if (idea != null)
                    handler.sendEmptyMessage(LOAD_FINISH);
                else {
                }
            }
        });

    }

    /**
     * 设置高度
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        System.out.println("aaa===" + totalHeight);
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 初始化界面
     */
    private void intiView() {
        setTvTitle("灵感详情");
        setRightText("评论");

        tvWhat = (TextView) findViewById(R.id.tv_idea_detail_what);
        tvName = (TextView) findViewById(R.id.tv_idea_detail_user_name);
        tvFrom = (TextView) findViewById(R.id.tv_idea_detail_from);
        tvTime = (TextView) findViewById(R.id.tv_idea_detail_time);
        tvBad = (TextView) findViewById(R.id.tv_idea_detail_bad);
        tvGood = (TextView) findViewById(R.id.tv_idea_detail_good);
        tvWhy = (TextView) findViewById(R.id.tv_idea_detail_why);
        tvHow = (TextView) findViewById(R.id.tv_idea_detail_how);
        tvDir = (TextView) findViewById(R.id.tv_idea_detail_dir);

        tvTlz = (TextView) findViewById(R.id.tv_idea_detail_tlz);
        tvWill = (TextView) findViewById(R.id.tv_idea_detail_will_enter);
        tvViews = (TextView) findViewById(R.id.tv_idea_detail_views);
        cvHead = (CircleImageView) findViewById(R.id.cv_idea_detail_user_head);

        comments = new ArrayList<IdeaComment>();
        lvComments = (ScrollXListView) findViewById(R.id.xlv_idea_detail_comments);
        commentAdapter = new ItemIdeaCommentAdapter(IdeaDetailActivity.this, comments);
        lvComments.setAdapter(commentAdapter);
        lvComments.setPullLoadEnable(false);
        lvComments.setPullRefreshEnable(false);
        lvComments.setVerticalScrollBarEnabled(false);
        lvComments.setXListViewListener(this);

        badSelected = getResources().getDrawable(R.mipmap.idea_detail_bad_selected);
        badSelected.setBounds(0, 0, badSelected.getMinimumWidth(), badSelected.getMinimumHeight());
        goodNormal = getResources().getDrawable(R.mipmap.idea_detail_good_normal);
        goodNormal.setBounds(0, 0, goodNormal.getMinimumWidth(), goodNormal.getMinimumHeight());
        goodSelected = getResources().getDrawable(R.mipmap.idea_detail_good_selected);
        goodSelected.setBounds(0, 0, goodSelected.getMinimumWidth(), goodSelected.getMinimumHeight());
        badNormal = getResources().getDrawable(R.mipmap.idea_detail_bad_normal);
        badNormal.setBounds(0, 0, badNormal.getMinimumWidth(), badNormal.getMinimumHeight());

        tvWill.setClickable(false);
        tvWill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppContext.getInstance().getUserId() == idea.getUser_id()) {
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("iId", idea.getId());
//                    UIHelper.showActivity(IdeaDetailActivity.this, NewTlzActivity.class, bundle);
//                    tvWill.setText("已有(" + idea.getWillers() + "人)关注");
                } else {
                    ThreadPoolUtils.execute(new Runnable() {
                        @Override
                        public void run() {
                            ideaService.doWillJoin(idea.getId());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    UIHelper.ToastMessage(IdeaDetailActivity.this, "关注成功");
                                    tvWill.setText("已有(" + idea.getWillers() + 1 + "人)关注");
                                }
                            });
                        }
                    });
                }
            }
        });

        tvTlz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果是自己的想法，讨论组点击后直接进入聊天
                if (AppContext.getInstance().getUserId() == idea.getUser_id()) {
                    //进入聊天
                    Bundle bundle = new Bundle();
                    bundle.putInt("chatType", ChatActivity.CHATTYPE_TLZ);
                    bundle.putString("name", idea.getTlz_name());
                    bundle.putInt("id", idea.getTlz_id());
                    UIHelper.showActivity(IdeaDetailActivity.this, ChatActivity.class, bundle);
                } else {
                    //查看信息
                    Bundle bundle = new Bundle();
                    bundle.putString("name", idea.getTlz_name());
                    bundle.putInt("id", idea.getTlz_id());
                    UIHelper.showActivity(IdeaDetailActivity.this, TlzDetailActivity.class, bundle);
                }
            }
        });
        pd = new ProgressDialog(this);
        pd.setMessage("操作成功");
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        lvComments.setOnItemClickListener(this);
        lvComments.setOnItemLongClickListener(this);

        tvGood.setOnClickListener(this);
        tvBad.setOnClickListener(this);
        cvHead.setOnClickListener(this);
    }

    @Override
    public void rightOperation() {
        //发布评论
        if (!AppContext.getInstance().getIsLogined()) {
            UIHelper.showNotLogined(IdeaDetailActivity.this);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("ideaId", ideaId);
        UIHelper.showActivity(IdeaDetailActivity.this, IdeaReplyActivity.class, bundle);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("reply", comments.get(position - 1));
        bundle.putInt("ideaId", ideaId);
        UIHelper.showActivity(IdeaDetailActivity.this, IdeaReplyDetailActivity.class, bundle);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_idea_detail_good:
                //点赞
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(IdeaDetailActivity.this);
                    return;
                }
                if (idea != null) {
                    tvGood.setCompoundDrawables(goodSelected, null, null, null);
                    tvGood.setText(idea.getGood() + 1 + "");
                    tvGood.setTextColor(Color.RED);
                    tvBad.setCompoundDrawables(badNormal, null, null, null);
                    tvBad.setTextColor(Color.BLACK);
                    tvBad.setText(idea.getBad() + "");
                    praiseAction = 0;
                }
                break;
            case R.id.tv_idea_detail_bad:
                //点道赞
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(IdeaDetailActivity.this);
                    return;
                }
                if (idea != null) {
                    tvGood.setCompoundDrawables(goodNormal, null, null, null);
                    tvGood.setTextColor(Color.BLACK);
                    tvGood.setText(idea.getGood() + "");
                    tvBad.setCompoundDrawables(badSelected, null, null, null);
                    tvBad.setTextColor(Color.RED);
                    tvBad.setText(idea.getBad() + 1 + "");
                    praiseAction = 1;
                }
                break;
            case R.id.cv_idea_detail_user_head:
                if (idea == null) break;
                Bundle bundle = new Bundle();
                bundle.putInt("userId", idea.getUser_id());
                UIHelper.showActivity(IdeaDetailActivity.this, UserInfoActivity.class, bundle);
                break;
        }
    }

    private ProgressDialog pd;

    private int praiseAction = -1;

    @Override
    public void onPause() {
        //发出点赞请求
        if (praiseAction == 0 || praiseAction == 1) {
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    ideaService.praise(ideaId, praiseAction == 0);
                }
            });
        }
        super.onPause();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        return false;
    }

    @Override
    public void onRefresh() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                comments = ideaService.getComments(ideaId, page, 0);
                if (comments != null) {
                    handler.sendEmptyMessage(LOAD_REFRESH);
                    if (comments.size() < 20) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                lvComments.setPullLoadEnable(false);
                            }
                        });
                    }
                } else {
                    lvComments.stopRefresh();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            lvComments.setPullLoadEnable(false);
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onLoadMore() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                List<IdeaComment> mideas = new ArrayList<IdeaComment>();
                mideas = ideaService.getComments(ideaId, ++page, 0);
                if (mideas != null) {
                    comments.addAll(mideas);
                    handler.sendEmptyMessage(LOAD_MORE);
                    if (comments.size() < 20) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                lvComments.setPullLoadEnable(false);
                            }
                        });
                    }
                } else {
                    page--;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            lvComments.setPullLoadEnable(false);
                        }
                    });
                    handler.sendEmptyMessage(LOAD_MORE);
                }
            }
        });
    }
}
